package uform.ui.comp;
import uform.property.Property;
import thx.validation.Option;

/**
 * ...
 * @author Franco Ponticelli
 */

class SelectControl<T> extends Control<T>
{
	var options : Array<Option<T>>;
	public var imagePath(default, null) : Property<String>;
	public var labelTranslation(default, null) : Property<Bool>;
	public function new(name : String, ?value : T)
	{
		super(name, value);
		this.value = new Property();
		this.imagePath = new Property();
		this.labelTranslation = new Property(true);
		this.value.onChange.add(internalValidate);
		this.options = [];
	}
	
	public function addOption(option : Option<T>)
	{
		options.push(option);
	}
	
	public function addValue(value : T, ?label : String)
	{
		addOption({
			value : value,
			label : null == label ? Std.string(value) : label
		});
	}
	
	public function clearOptions()
	{
		this.options = [];
		this.value.set(null);
	}
	
	public function getOptions()
	{
		return options.iterator();
	}
	
	function internalValidate()
	{
		if (value.isNull())
			return;
		var v = value.get();
		if (!Lambda.exists(options, function(option)  return option.value == v))
			value.set(null);
	}

	override function dispose()
	{
		imagePath.onChange.clear();
		imagePath = null;
		super.dispose();
	}
}